package com.example.demo.controller;

import com.example.demo.entity.WechatUser;
import com.example.demo.service.UserService;
import com.example.demo.vo.DataView;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RequestMapping(value = "/user")
@RestController
public class WechatUserController {

    @Value("${user.image}")
    private String path;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/updateWechatUserName")
    public DataView updateWechatUserName(String username,HttpServletRequest httpServletRequest) {
        DataView dataView = new DataView();
        String token = httpServletRequest.getHeader("token");
        WechatUser wechatUser = userService.queryToken(token);
        if (wechatUser == null) {
            dataView.setMsg("用户不存在");
            dataView.setCode(300);
            return dataView;
        }
        wechatUser.setUsername(username);
        userService.updateById(wechatUser);
        dataView.setCode(200);
        dataView.setMsg("用户名称更新成功");
        return dataView;
    }


    @RequestMapping(value ="/updateHeaderImage")
    public DataView updateHeaderImage(@RequestParam(value = "imageFile")MultipartFile imageFile, HttpServletRequest request) throws IOException {
        DataView dataView = new DataView();
        String token = request.getHeader("token");
        WechatUser wechatUser = userService.queryToken(token);
        if (wechatUser == null) {
            dataView.setMsg("用户不存在");
            dataView.setCode(300);
            return dataView;
        }
        if(imageFile.isEmpty())
        {
            dataView.setCode(400);
            dataView.setMsg("读取错误，请联系管理员");
            return dataView;
        }
        String originalFilename = imageFile.getOriginalFilename();
        String openid = wechatUser.getOpenid();
        String imagePath = path+openid+"\\"+originalFilename;
        File file = new File(imagePath);
        if(!file.exists())
        {
            file.mkdirs();
        }
        imageFile.transferTo(file);
        dataView.setCode(200);
        dataView.setMsg("用户头像更新成功");
        return dataView;
    }
}
